package game;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener ;
import java.awt.event.MouseEvent ;
import java.awt.event.InputEvent ;
import java.awt.image.MemoryImageSource;
import java.util.LinkedList;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.Timer;

public class Dictator extends Game {
    int disable = 0;
    Double increment;
    Double money_won = 0.0, p1_init_money = 4.0, money_given = 0.0 ;
    int totalTime=60,secs = totalTime, timeTaken=0;
    Timer time = new Timer(1000, new TimeListener());
    String state="init";

	/** List of values that user can choose to send. Used in chooser JList. */
	LinkedList<String> moneyValues = new LinkedList<String>();

	/** Number of values to display in the chooser JList. */
	final int LIST_SIZE = 5;

	/** Half of list size. */
	int halfList;

	/** Maximum number of values the user could possibly choose given the
	 increment, and starting and stopping values. */
	int maxValues;

	/** List index we've displayed for the chooser list. */
	int listIndex = 0;

	// End game statuses.
	final int EG_NORMAL = 0;
	final int EG_TIMEOUT = 1;

    /** Creates new form Dictator */
    public Dictator (String params, int currentRep){
        super();
//        super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
//        javax.swing.plaf.InternalFrameUI ui = this.getUI();
//        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		String paramPart[] = params.split (",");
        p1_init_money = Double.parseDouble (paramPart[2]);
        increment = Double.parseDouble (paramPart[3]);
		this.params = params;
		repTot = Integer.parseInt (paramPart[1]);
		repNum = currentRep;

        initComponents();
        
        l3.setText (String.format ("$%.2f", p1_init_money));
        this.setVisible(true);
        setLocation(screenSize.width/2-400, screenSize.height/2-300);

        runner.addMouseListener( new Dictator.CheckMouse() ) ;
        addMouseListener( new Dictator.CheckMouse() ) ;
		this.getGlassPane().addMouseListener(new Dictator.CheckMouse());

        l11.setIcon(new ImageIcon(this.getClass()
                .getResource("/images/redAddMoney.png")));
        l10.setIcon(new ImageIcon(this.getClass()
                .getResource("/images/greenGive.png")));
        
        time.start();
        int min = secs/60;
        int sec = secs%60;
        lblTime.setText(min+":"+((sec<10)?"0":"")+sec);

		// Assuming no loss of precision.
		maxValues = (int) (p1_init_money / increment) + 1;
		halfList = (int) Math.floor (LIST_SIZE / 2);
		int numValues = maxValues - halfList + LIST_SIZE;
		for (listIndex = maxValues-halfList;
			listIndex < numValues; listIndex++) {
			moneyValues.add (String.format ("$%.2f",
				increment * (listIndex % maxValues)));
		}
		listIndex--;
		moneyList.setListData (moneyValues.toArray(new String [LIST_SIZE]));
		moneyList.setSelectedIndex (halfList);
		moneyList.addMouseListener (new Dictator.CheckMouse());

        hideMouse();
    }

    public Dictator() {
        super();
//        super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
        javax.swing.plaf.InternalFrameUI ui = this.getUI();
        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        p1_init_money = 4.0;
        increment = 0.25;
        initComponents();

		l3.setText (String.format ("$%.2f", p1_init_money));
        this.setVisible(true);
        setLocation(screenSize.width/2-400, screenSize.height/2-300);

        runner.addMouseListener( new Dictator.CheckMouse() ) ;
        addMouseListener( new Dictator.CheckMouse() ) ;

        l11.setIcon(new ImageIcon(this.getClass()
                .getResource("/images/redAddMoney.png")));
        l10.setIcon(new ImageIcon(this.getClass()
                .getResource("/images/greenGive.png")));
        
        time.start();
        int min = secs/60;
        int sec = secs%60;
        lblTime.setText(min+":"+((sec<10)?"0":"")+sec);

        hideMouse();
    }

	/**
     * Shift the money list to increase by one place.
     */
    private void incrementMoneyList() {
		listIndex++;
		moneyValues.remove();
		moneyValues.add (String.format ("$%.2f",
			increment * (listIndex % maxValues)));
		moneyList.setListData (
			moneyValues.toArray(new String [LIST_SIZE]));
		moneyList.setSelectedIndex (halfList);
    }

	/**
	 * Writes to the logs when the game ends.
	 */
	public void logEndGame (int status) {
		String payment = "";
		String opponentPay = "";
		String player = "1";
		if (currGame.equals("Trust-Dictator")) player = "";

		if (status == EG_NORMAL) {
			String money =
				moneyList.getSelectedValue().toString().substring (1);
			payment = String.format ("$%.2f", money_won);
			opponentPay = String.format ("$%.2f", Double.parseDouble(money));
		}
		else if (status == EG_TIMEOUT) {
			payment = "TimeOut";
			opponentPay = "TimeOut";
		}
		else {}

		timeTaken = totalTime - secs;

		writeLog (playerId + "," + player + ",\"" + params + "\"," + repNum
			+ "," + repTot + "," + payment + "," + opponentPay);
		writeGameLog (playerId + "," + timeTaken + "," + opponentPay);
	}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        l5 = new javax.swing.JLabel();
        l2 = new javax.swing.JLabel();
        l10 = new javax.swing.JLabel();
        l3 = new javax.swing.JLabel();
        l4 = new javax.swing.JLabel();
        l11 = new javax.swing.JLabel();
        lblTime = new javax.swing.JLabel();
        moneyScroll = new javax.swing.JScrollPane();
        moneyList = new javax.swing.JList();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(null);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setPreferredSize(new java.awt.Dimension(800, 600));

        l5.setFont(new java.awt.Font("Calibri", 1, 28));
        l5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        l2.setFont(new java.awt.Font("Calibri", 1, 28)); // NOI18N
        l2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        l2.setText("You have");

        l10.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        l10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redBtn.png"))); // NOI18N

        l3.setFont(new java.awt.Font("Calibri", 1, 28));
        l3.setForeground(new java.awt.Color(51, 102, 255));

        l4.setFont(new java.awt.Font("Calibri", 1, 28));
        l4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        l4.setText("How much would you like to give to other player ?");

        l11.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        l11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redBtn.png"))); // NOI18N

        lblTime.setFont(new java.awt.Font("Calibri", 1, 36));
        lblTime.setForeground(new java.awt.Color(153, 102, 0));
        lblTime.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hrGlass.png"))); // NOI18N
        lblTime.setText("3:00");

        moneyList.setFont(new java.awt.Font("Tahoma", 1, 24));
        moneyList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "$0.00", "$0.25", "$0.50", "$0.75", "$1.00" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        moneyList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        moneyList.setVisibleRowCount(5);
        moneyList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                moneyListValueChanged(evt);
            }
        });
        moneyScroll.setViewportView(moneyList);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(lblTime, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 790, Short.MAX_VALUE)
                .add(10, 10, 10))
            .add(layout.createSequentialGroup()
                .add(355, 355, 355)
                .add(moneyScroll, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 128, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(317, Short.MAX_VALUE))
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(299, 299, 299)
                            .add(l2)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(l3)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 378, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(l5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 790, Short.MAX_VALUE)
                        .add(layout.createSequentialGroup()
                            .add(60, 60, 60)
                            .add(l11)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 80, Short.MAX_VALUE)
                            .add(l10)
                            .add(50, 50, 50))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, l4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 780, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(lblTime)
                .add(155, 155, 155)
                .add(moneyScroll, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(233, Short.MAX_VALUE))
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(79, 79, 79)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(l3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(l2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(42, 42, 42)
                    .add(l4)
                    .add(112, 112, 112)
                    .add(l5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 71, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(18, 18, 18)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(l11)
                        .add(l10))
                    .addContainerGap(110, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	/**
	 * Don't let subject change the value of the list.
	 *
	 * @param evt
	 */
	private void moneyListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_moneyListValueChanged
		moneyList.setSelectedIndex (halfList);
	}//GEN-LAST:event_moneyListValueChanged

    @Override
    public synchronized void addMouseListener(MouseListener l) {
        super.addMouseListener(l);
    }

    class CheckMouse implements MouseListener{
         public void mousePressed(MouseEvent e) { hideMouse(); }
         public void mouseReleased(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mouseClicked(MouseEvent e) {
			int modifiers = e.getModifiers();
            if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
                if(state.equals("end")) {
                } else {
                    incrementMoneyList();
                }
            }
            if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {}
            if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
                if(state.equals("end")) {}

				if(state.equals("init")) {
					String money =
						moneyList.getSelectedValue().toString().substring (1);
					money_won = p1_init_money - Double.parseDouble(money);
					l5.setText("") ;//You get %.2f", money_won));
					l10.setVisible(false);
					l11.setVisible(false);
					state="end";
					logEndGame (EG_NORMAL);
					totalMoneyWon += money_won ;
					System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
					setVisible(false);
                    free=true;
					time.stop();
				}
			}
        }
    }

    class TimeListener implements ActionListener {
    	 public void actionPerformed(ActionEvent e) {
    		secs--;
            if(secs>=0) {
                int min = secs/60;
                int sec = secs%60;
                lblTime.setText(min+":"+((sec<10)?"0":"")+sec);
            }
            if(secs==0) {
                //time.stop();
                l11.setVisible(false);
                l10.setVisible(false);
                state="end";
                l2.setText(null);
                l3.setText(null);
                l5.setText("Sorry, your time is up.");
                logEndGame (EG_TIMEOUT);
                totalMoneyWon += 0.0 ;
                System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
            }
            if(secs==-6) {
                time.stop();
                try {
                    setVisible(false);
                    free=true;
                } catch(Exception ex) {
                    ex.printStackTrace();
                    logError(ex);
                }
            }
    	}

    }

    private void hideMouse() {
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisibleCursor");
        this.getGlassPane().setCursor(transparentCursor);
		this.getGlassPane().setVisible(true);
        runner.setCursor(transparentCursor);
    }


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JFrame main = new JFrame();
                    JDesktopPane dPane = new JDesktopPane();
                    Dictator frame = new Dictator();
                    main.setSize(820, 620);
                    dPane.add(frame);
                    main.add(dPane);
                    main.setVisible(true);
                    dPane.setVisible(true);
                    frame.setSelected(true);
                    frame.setVisible(true);
                } catch(Exception ex) {
                    ex.printStackTrace();
                };
            }
        });
    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel l10;
    private javax.swing.JLabel l11;
    private javax.swing.JLabel l2;
    private javax.swing.JLabel l3;
    private javax.swing.JLabel l4;
    private javax.swing.JLabel l5;
    private javax.swing.JLabel lblTime;
    private javax.swing.JList moneyList;
    private javax.swing.JScrollPane moneyScroll;
    // End of variables declaration//GEN-END:variables

}
